package com.flyduck.vueshop.search.mq;

import com.flyduck.vueshop.common.core.utils.BeanUtils;
import com.flyduck.vueshop.common.rabbitmq.constant.SearchRabbitConstant;
import com.flyduck.vueshop.product.feign.RemoteProductFeignClient;
import com.flyduck.vueshop.product.vo.RemoteProductRespVO;
import com.flyduck.vueshop.search.document.EsProductDoc;
import com.flyduck.vueshop.search.repository.EsProductDocRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * @program: vueshop
 * @description:
 * @author: flyduck
 * @create: 2024-05-25 07:56
 **/
@Slf4j
@Component
public class SearchConsumer {

    @Resource
    private RemoteProductFeignClient remoteProductFeignClient;
    @Resource
    private EsProductDocRepository esProductDocRepository;

    @RabbitListener(queues = SearchRabbitConstant.PRODUCT_SEARCH_CREATE_QUEUE)
    public void createListener(Long productId){
        RemoteProductRespVO remoteProductRespVO = remoteProductFeignClient.getProductById(productId).getData();
        //查询不到，或者下架了，需要从es删除
        if(remoteProductRespVO == null || !remoteProductRespVO.getIsOnSale()){
            esProductDocRepository.deleteById(productId);
            log.info("【监听到商品创建】从es删除商品成功,productId={}", productId);
        }else {
            EsProductDoc esProductDoc = BeanUtils.toBean(remoteProductRespVO, EsProductDoc.class);
            esProductDocRepository.save(esProductDoc);
            log.info("【监听到商品创建】保存商品到es成功,productId={}", productId);
        }
    }

    @RabbitListener(queues = SearchRabbitConstant.PRODUCT_SEARCH_DELETE_QUEUE)
    public void deleteListener(List<Long> productIds){
        esProductDocRepository.deleteAllById(productIds);
        log.info("【监听到商品删除】从es删除商品成功,productIds={}", productIds);
    }
}
